package com.atguigu.springcloud.config.loadbakanced;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

@Component
public class MyLB implements LoadBanced{
	
	private AtomicInteger atomicInteger = new AtomicInteger(0);
	/**
	 * rest 接口的请求计数
	 * @return
	 */
	public final int getAndIncrement() {
		int current;
		int next;
		do {
			current = this.atomicInteger.get();
			next = current >= Integer.MAX_VALUE?0:current+1;
		} while (!this.atomicInteger.compareAndSet(current, next));
		System.out.println("********第几次访问的次数 ： next********"+next);
		return next;
	}
	/**
	 * 轮询算法：rest 接口被第几次请求 % 服务器集群总数量 = 实际调用服务器位置下标 ，
	 *  每次服务器重启后rest 接口请求计数从1开始
	 */
	@Override
	public ServiceInstance instance(List<ServiceInstance> serviceInstance) {
		int index = getAndIncrement() % serviceInstance.size();
		return serviceInstance.get(index);
	}

}
